package com.kco.generate.java;

import com.kco.generate.config.ColumnsBean;
import com.kco.generate.config.TableBean;
import org.apache.commons.lang3.StringUtils;

import static com.kco.generate.config.Utils.saveFile;

/**
 * 创建bean java文件
 * Created by 666666 on 2017/9/26.
 */
public final class CreateDaoXml {

    public static void buildFile(TableBean tableBean) {
        StringBuilder sb = new StringBuilder();
        String basePackage = tableBean.getBasePackage();
        String className = tableBean.getClassName();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
                .append("<!DOCTYPE mapper\n")
                .append("        PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\n")
                .append("        \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n")
                .append("<mapper namespace=\"com.ics.cmsadmin.dao."+basePackage+"."+className+"Dao\">\n\n")
                .append(buildResultMap(tableBean))
                .append(buildCommonColumn(tableBean))
                .append(buildQueryById(tableBean))
                .append(buildInsert(tableBean))
                .append(buildUpdate(tableBean))
                .append(buildDelete(tableBean))
                .append(buildCommonWhere(tableBean))
                .append(buildList(tableBean))
                .append(buildFindOne(tableBean))
                .append(buildCount(tableBean))
                .append("</mapper>\n");
        saveFile( "mapper/" + tableBean.getClassName() + "Dao.xml", sb.toString());
    }

    private static String buildFindOne(TableBean tableBean) {
        String s = tableBean.getClassName().substring(0, 1).toLowerCase() + tableBean.getClassName().substring(1);
        StringBuilder sb = new StringBuilder();
        sb.append("    <select id=\"findOne\" resultMap=\""+s+"ResultMap\">\n")
                .append("        SELECT <include refid=\"commonColumns\"/> FROM ").append(tableBean.getTableName()).append("\n")
                .append("        <include refid=\"commonWhere\"/>\n")
                .append("        LIMIT 1\n")
                .append("    </select>\n\n");
        return sb.toString();
    }

    private static String buildResultMap(TableBean tableBean) {
        StringBuilder sb = new StringBuilder();
        String s = tableBean.getClassName().substring(0, 1).toLowerCase() + tableBean.getClassName().substring(1);
        String basePackage = tableBean.getBasePackage();
        String className = tableBean.getClassName();
        sb.append("\t<resultMap id=\"" + s + "ResultMap\" type=\"com.ics.cmsadmin.model."+basePackage+"."+className+"Bean\">\n")
                .append("\t\t<id column=\"" + tableBean.getPrimaryColumnKey() + "\" property=\"" + tableBean.getPrimaryPropertyKey() + "\"/>\n");

        for (ColumnsBean columnsBean : tableBean.getColumnsBeans()){
            sb.append("\t\t<result column=\""+ columnsBean.getColumnName() +"\" property=\""+ columnsBean.getPropertyName() +"\"/>\n");
        }

        sb.append("\t</resultMap>\n\n");
        return sb.toString();
    }

    private static String buildCommonColumn(TableBean tableBean) {
        StringBuilder sb = new StringBuilder();
        sb.append("    <sql id=\"commonColumns\">\n");
        for (ColumnsBean bean : tableBean.getColumnsBeans()){
            sb.append("        ").append(bean.getColumnName()).append(",\n");
        }
        sb.delete(sb.length()-2, sb.length());
        sb.append("\n    </sql>\n\n");
        return sb.toString();
    }

    private static String buildCommonWhere(TableBean tableBean) {
        StringBuilder sb = new StringBuilder();
        sb.append("    <sql id=\"commonWhere\">\n");
        sb.append("        <where>\n");
        for (ColumnsBean bean : tableBean.getColumnsBeans()){
            if (StringUtils.equals(bean.getColumnName(), "updator") ||
                    StringUtils.equals(bean.getColumnName(), "create_time") ||
                    StringUtils.equals(bean.getColumnName(), "creator") ||
                    StringUtils.equals(bean.getColumnName(), "update_time") ){
                continue;
            }
            sb.append("            <if test=\"@org.apache.commons.lang3.StringUtils@isNotBlank(bean."+bean.getPropertyName()+")\">\n")
                    .append("                AND ").append(bean.getColumnName()).append(" = #{bean.").append(bean.getPropertyName()).append("}\n");
            sb.append("            </if>\n");
        }
        sb.append("        </where>\n");
        sb.append("    </sql>\n\n");
        return sb.toString();
    }

    private static String buildCount(TableBean tableBean) {
        StringBuilder sb = new StringBuilder();

        sb.append("    <select id=\"count\" resultType=\"long\">\n")
                .append("        SELECT count(*) FROM ").append(tableBean.getTableName()).append("\n")
                .append("        <include refid=\"commonWhere\"/>\n")
                .append("    </select>\n\n");
        return sb.toString();
    }

    private static String buildList(TableBean tableBean) {
        String s = tableBean.getClassName().substring(0, 1).toLowerCase() + tableBean.getClassName().substring(1);
        StringBuilder sb = new StringBuilder();
        sb.append("    <select id=\"list\" resultMap=\""+s+"ResultMap\">\n")
                .append("        SELECT <include refid=\"commonColumns\"/> FROM ").append(tableBean.getTableName()).append("\n")
                .append("        <include refid=\"commonWhere\"/>\n")
                .append("        LIMIT #{page.offset},#{page.pageSize}\n")
                .append("    </select>\n\n");
        return sb.toString();
    }

    private static String buildDelete(TableBean tableBean) {
        StringBuilder sb = new StringBuilder();
        sb.append("    <delete id=\"delete\">\n");
        sb.append("        DELETE FROM "+tableBean.getTableName()+" WHERE "+tableBean.getPrimaryColumnKey()+" = #{id}\n");
        sb.append("    </delete>\n\n");
        return sb.toString();
    }

    private static String buildUpdate(TableBean tableBean) {
        StringBuilder sb = new StringBuilder();
        sb.append("    <update id=\"update\">\n");
        sb.append("        UPDATE ").append(tableBean.getTableName()).append("\n");
        sb.append("        SET \n");
        for (ColumnsBean bean : tableBean.getColumnsBeans()){
            if (StringUtils.equals(bean.getColumnName(), tableBean.getPrimaryColumnKey()) ||
                    StringUtils.equals(bean.getColumnName(), "create_time") ||
                    StringUtils.equals(bean.getColumnName(), "creator") ||
                    StringUtils.equals(bean.getColumnName(), "update_time") ){
                continue;
            }
            sb.append("            <if test=\"bean."+bean.getPropertyName()+" != null and bean."+bean.getPropertyName()+" != ''\">\n")
                    .append("                ").append(bean.getColumnName()).append(" = #{bean.").append(bean.getPropertyName()).append("},\n");
            sb.append("            </if>\n");
        }
        sb.append("            " + tableBean.getPrimaryColumnKey()+" = #{id}\n");
        sb.append("        WHERE ").append(tableBean.getPrimaryColumnKey()).append(" = ").append("#{id}\n");
        sb.append("    </update>\n\n");
        return sb.toString();
    }

    private static String buildInsert(TableBean tableBean) {
        String className = tableBean.getClassName();
        String basePackage = tableBean.getBasePackage();
        StringBuilder sb = new StringBuilder();
        sb.append("    <insert id=\"insert\" parameterType=\"com.ics.cmsadmin.model."+basePackage+"."+className+"Bean\">\n");
        sb.append("        INSERT INTO ").append(tableBean.getTableName()).append(" (\n");
        sb.append("            ").append(tableBean.getPrimaryColumnKey()).append(",\n");
        for (ColumnsBean bean : tableBean.getColumnsBeans()){
            if (StringUtils.equals(bean.getColumnName(), tableBean.getPrimaryColumnKey()) ||
                    StringUtils.equals(bean.getColumnName(), "updator") ||
                    StringUtils.equals(bean.getColumnName(), "update_time") ){
                continue;
            }
            if (StringUtils.equals(bean.getColumnName(), "create_time")){
                sb.append("            create_time,\n");
                continue;
            }
            sb.append("            <if test=\"bean."+bean.getPropertyName()+" != null and bean."+bean.getPropertyName()+" != ''\">\n")
                    .append("                ").append(bean.getColumnName()).append(",\n");
            sb.append("            </if>\n");
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        sb.append("        ) VALUES ( \n");
        sb.append("            #{bean.").append(tableBean.getPrimaryPropertyKey()).append("},\n");
        for (ColumnsBean bean : tableBean.getColumnsBeans()){
            if (StringUtils.equals(bean.getColumnName(), tableBean.getPrimaryColumnKey()) ||
                    StringUtils.equals(bean.getColumnName(), "updator") ||
                    StringUtils.equals(bean.getColumnName(), "update_time") ){
                continue;
            }
            if (StringUtils.equals(bean.getColumnName(), "create_time")){
                sb.append("            CURRENT_TIMESTAMP,\n");
                continue;
            }
            sb.append("            <if test=\"bean."+bean.getPropertyName()+" != null and bean."+bean.getPropertyName()+" != ''\">\n")
                    .append("                #{bean.").append(bean.getPropertyName()).append("},\n");
            sb.append("            </if>\n");
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        sb.append("        )\n");
        sb.append("    </insert>\n\n");
        return sb.toString();
    }

    private static String buildQueryById(TableBean tableBean) {
        StringBuilder sb = new StringBuilder();
        String s = tableBean.getClassName().substring(0, 1).toLowerCase() + tableBean.getClassName().substring(1);
        sb.append("    <select id=\"queryById\" resultMap=\""+s+"ResultMap\">\n");
        sb.append("        SELECT <include refid=\"commonColumns\"/>");
        sb.append(" FROM ").append(tableBean.getTableName()).append("\n");
        sb.append("        WHERE ")
                .append(tableBean.getPrimaryColumnKey())
                .append(" = #{id}\n");
        sb.append("    </select>\n\n");
        return sb.toString();
    }
}
